package com.ruoyi.mobile.service.impl;

import cn.hutool.core.date.DateUtil;
import cn.hutool.core.util.RandomUtil;
import com.google.gson.Gson;
import com.qiniu.common.QiniuException;
import com.qiniu.http.Response;
import com.qiniu.storage.Configuration;
import com.qiniu.storage.Region;
import com.qiniu.storage.UploadManager;
import com.qiniu.storage.model.DefaultPutRet;
import com.qiniu.util.Auth;
import com.ruoyi.common.core.domain.entity.SysUser;
import com.ruoyi.common.utils.SecurityUtils;
import com.ruoyi.mobile.service.IQiniuService;
import org.springframework.stereotype.Service;

import java.io.ByteArrayInputStream;

@Service
public class QiniuServiceImpl implements IQiniuService {

    @Override
    public String upload(ByteArrayInputStream byteInputStream, Integer type) {

        Long userId = SecurityUtils.getLoginUser().getUser().getUserId();

        Configuration cfg = new Configuration(Region.region2());
        cfg.resumableUploadAPIVersion = Configuration.ResumableUploadAPIVersion.V2;// 指定分片上传版本
        cfg.useHttpsDomains = false;
        UploadManager uploadManager = new UploadManager(cfg);

        //...生成上传凭证，然后准备上传
        String accessKey = "qKNdoHXVWRtJsjI8l10EvT3B3pd3ZlSK-rzjSmKq";
        String secretKey = "uVTz1YJpB0zHRlPntvpWhqsiNZk-LwpjWRG0_qo7";
        String bucket = "bd2h";
        //默认不指定key的情况下，以文件内容的hash值作为文件名
        String key = null;
        String filename = String.valueOf(userId) +"_" + DateUtil.format(DateUtil.date(), "yyyyMMddHHmmss") + String.valueOf(RandomUtil.randomInt(10000000, 99999999));
        if (1 == type) {
            key = "avatar/" + filename;
        } else if (2 == type) {
            key = "im/" + filename;
        } else if (3 == type) {
            key = "medical/" + filename;
        } else if (4 == type) {
            key = "article/" + filename;
        } else if (5 == type) {
            key = "banner/" + filename;
        } else if (6 == type) {
            key = "video_cover/" + filename;
        }
        
        Auth auth = Auth.create(accessKey, secretKey);
        String upToken = auth.uploadToken(bucket);
        try {
            Response response = uploadManager.put(byteInputStream,key,upToken,null, null);
            //解析上传成功的结果
            DefaultPutRet putRet = new Gson().fromJson(response.bodyString(), DefaultPutRet.class);
            System.out.println(putRet.key);
            System.out.println(putRet.hash);
            return "https://qny.bravo.love/" + putRet.key;
        } catch (QiniuException ex) {
            Response r = ex.response;
            System.err.println(r.toString());
            try {
                System.err.println(r.bodyString());
            } catch (QiniuException ex2) {
                //ignore
            }
        }
        return "";

    }

}
